package com.kai.admin.security.filter;

import com.kai.admin.security.constants.SecurityConstants;
import com.kai.admin.enums.AdminErrorCodeConstants;
import com.kai.admin.security.service.CaptchaService;
import com.kai.auth.util.PatternUtil;
import com.kai.common.data.Result;
import com.kai.common.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码过滤器
 */
@Slf4j
@Component
public class CaptchaAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private CaptchaService captchaService;

    private static final String CAPTCHA_KEY = "captchaKey";

    private static final String CAPTCHA_CODE = "captchaCode";

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain chain) throws ServletException, IOException {
        String captchaKey = WebUtil.getParameter(CAPTCHA_KEY);
        String captchaCode = WebUtil.getParameter(CAPTCHA_CODE);

        if (StringUtils.isBlank(captchaKey) || StringUtils.isBlank(captchaCode)) {
            WebUtil.writeJson(Result.fail(AdminErrorCodeConstants.CAPTCHA_MISSING));
            return;
        }

        // 校验验证码
        if (!captchaService.verifyCaptcha(captchaKey, captchaCode)) {
            WebUtil.writeJson(Result.fail(AdminErrorCodeConstants.INVALID_CAPTCHA));
            return;
        }

        // 删除验证码
        captchaService.deleteCaptcha(captchaKey);

        // 继续过滤链
        chain.doFilter(request, response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        return !PatternUtil.matches(SecurityConstants.LOGIN_URL, request.getRequestURI());
    }
}
